const { ipcRenderer } = require('electron');

let selectedFilePath = null;

async function loadFiles(files) {
    const fileList = document.getElementById('fileList');
    fileList.innerHTML = '';
    
    if (!files || files.length === 0) {
        const div = document.createElement('div');
        div.className = 'file-item';
        div.textContent = '没有找到文件';
        fileList.appendChild(div);
        return;
    }

    files.forEach(file => {
        const div = document.createElement('div');
        div.className = 'file-item';
        div.textContent = file.name;
        div.onclick = () => selectFile(file.path);
        fileList.appendChild(div);
    });
}

async function selectFile(filePath) {
    selectedFilePath = filePath;
    const content = await ipcRenderer.invoke('read-json-file', filePath);
    document.getElementById('fileContent').textContent = JSON.stringify(content, null, 2);
    
    // 更新选中状态
    document.querySelectorAll('.file-item').forEach(item => {
        item.classList.remove('selected');
        if (item.textContent === filePath.split('\\').pop()) {
            item.classList.add('selected');
        }
    });
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    // 监听初始文件列表
    ipcRenderer.on('initial-files', (event, data) => {
        loadFiles(data.files);
    });
    
    // 监听文件列表更新事件
    ipcRenderer.on('id-created', (event, data) => {
        loadFiles(data.files);
    });
    
    // 确定按钮
    document.getElementById('confirmBtn').onclick = async () => {
        if (selectedFilePath) {
            const content = await ipcRenderer.invoke('read-json-file', selectedFilePath);
            document.title = content.ID;
            
            // 将所选文件的路径传递到页面B
            window.location.href = `page-b.html?path=${encodeURIComponent(selectedFilePath)}`;
        }
    };
    
    // 新建按钮
    document.getElementById('newBtn').onclick = () => {
        document.getElementById('newIdModal').style.display = 'block';
    };

    // 保存新ID
    document.getElementById('saveNewId').onclick = () => {
        const newId = document.getElementById('newIdInput').value;
        if (newId) {
            ipcRenderer.send('create-new-id', newId);
            document.getElementById('newIdModal').style.display = 'none';
            document.getElementById('newIdInput').value = '';
        }
    };
    
    // 取消新建
    document.getElementById('cancelNewId').onclick = () => {
        document.getElementById('newIdModal').style.display = 'none';
        document.getElementById('newIdInput').value = '';
    };
}); 